package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.query.BidRequestQuery;
import cn.wolfcode.p2p.business.query.CreditTransferQuery;
import cn.wolfcode.p2p.business.service.IBidRequestService;
import cn.wolfcode.p2p.business.service.ICreditTransferService;
import cn.wolfcode.p2p.util.Constants;
import cn.wolfcode.p2p.util.JSONResult;
import cn.wolfcode.p2p.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

@Controller
public class InvestController {
        @Autowired
        private IBidRequestService bidRequestService;
        @Autowired
        private ICreditTransferService creditTransferService;

        @RequestMapping("invest")
        public String invest(){
                return "invest";
        }

        @RequestMapping("invest_list")
        public String investList(@ModelAttribute("qo")BidRequestQuery qo, Model model){
                if(qo.getBidRequestType()== Constants.BIDREQUEST_TYPE_NORMAL){
                        PageResult pageResult = bidRequestService.selectForList(qo);
                        model.addAttribute("pageResult",pageResult);
                        return "invest_list";

                }else{
                        CreditTransferQuery qo1 = new CreditTransferQuery();
                        qo1.setCurrentPage(qo.getCurrentPage());
                        qo1.setPageSize(qo.getPageSize());
                        qo1.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
                        PageResult pageResult = creditTransferService.queryMyTransfer(qo1);
                        model.addAttribute("pageResult",pageResult);
                        return "credittransfer_list";
                }
        }

        @RequestMapping("borrow_bid")
        @ResponseBody
        public JSONResult borrowBid(Long bidRequestId, BigDecimal amount){
                JSONResult jsonResult = new JSONResult();
                try {
                        bidRequestService.bid(bidRequestId,amount);
                    }catch (CustomException e ){
                        jsonResult.setMsg(e.getMessage());//自定义的异常,避免所有异常都返回同样的信息给客户
                    } catch (Exception e) {
                        e.printStackTrace();
                        jsonResult.setMsg("系统繁忙,请稍后再试");
                }
                 return jsonResult;
        }



}
